package com.citycloud.ccuap.tc.sync.controller;

import com.citycloud.ccuap.commons.application.ApplicationGlobalNames;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.json.TreeNode;
import com.citycloud.ccuap.commons.openapi.controller.base.BaseController;
import com.citycloud.ccuap.commons.sys.deptment.IDeptmentService;
import com.citycloud.ccuap.commons.sys.entity.SysDeptment;
import com.citycloud.ccuap.commons.sys.entity.SysProjectDeptmentRel;

import com.citycloud.ccuap.commons.sys.project.IProjectService;
import com.citycloud.ccuap.commons.web.util.ResolveRequest;
import com.citycloud.ccuap.tc.admin.datagroup.IDatagroupService;
import com.citycloud.ccuap.tc.admin.datagroup.SysDatagroupDTO;
import com.citycloud.ccuap.tc.admin.entity.SysDatagroup;
import com.citycloud.ccuap.tc.sync.repository.SysProjectDeptmentRelRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zjl
 * @date 2020/04/29 13:12
 */
@Api(tags = "公共接口控制类-YqCommonController", value = "YqCommonController")
@RestController
@RequestMapping("/v1/yq/common")
public class CommonController extends BaseController {
    protected static Logger logger = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    private IDeptmentService deptmentService;
    @Autowired
    @Qualifier("sysPDRepository")
    private SysProjectDeptmentRelRepository sysProjectDeptmentRelRepository;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IDatagroupService datagroupService;

    /**
     * 根据机构编号和站点id获取部门树
     *
     * @return
     */
    @ApiOperation(value = "根据机构编号和站点id获取部门树", notes = "站点管理员导入部门使用")
    @RequestMapping(value = "/getDeptTreeListByGroupIdAndProjectId", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getDeptTreeListByGroupIdAndProjectId(@RequestParam(value = "groupId") Long groupId, @RequestParam(value = "projectId") Long projectId) {

        List<SysDeptment> list = getDeptTreeListByGroupIdAndProjectId(groupId, ApplicationGlobalNames.DATA_STATUS_ENABLE, projectId);
        logger.error("liujw-开始-------站点管理员导入部门 集合---------------：{}",  StringUtils.join(list,","));
        List<SysProjectDeptmentRel> sysProjectDeptmentRels = sysProjectDeptmentRelRepository.findByProjectId(projectId);

        List<String> deptIds = sysProjectDeptmentRels.stream().filter(sysProjectDeptmentRel -> sysProjectDeptmentRel != null)
                .map(sysProjectDeptmentRel -> String.valueOf(sysProjectDeptmentRel.getDeptId())).collect(Collectors.toList());
        List<TreeNode> deptTreeList = deptListToTree(list, deptIds);
        //没有子节点同时当前部门没有子部门
        logger.error("liujw-结束-------------站点管理员导入部门 集合---------------：{}", StringUtils.join(deptTreeList,","));
        JSONData jsonData = new JSONData(deptTreeList);
        return jsonData;
    }

    @ApiOperation("根据用户编号获取全路径")
    @RequestMapping(value = "/getAllPath", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getAllPath() {
        Long userId = getLongParameter("userId");
        String sql = "select sg.full_path grouppath,sd.full_path deptpath,su.user_name  from sys_user su inner join sys_deptment sd on su.dept_id=sd.dept_id inner join sys_group sg on su.group_id=sg.group_id where su.user_id=" + userId;
        List<Map<String, Object>> list = projectService.selectList(sql, true);
        String allPath = null;
        if (list.size() > 0) {
            allPath = list.get(0).get("grouppath") + "/" + list.get(0).get("deptpath") + "/" + list.get(0).get("userName");
        }
        JSONData jsonData = new JSONData(allPath);
        return jsonData;
    }

    @ApiOperation("获取数据组")
    @RequestMapping(value = "/getDatagroup", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getDatagroup() throws Exception {
        SysDatagroupDTO sysDatagroupDto = new SysDatagroupDTO();
        ResolveRequest.fillData(request, sysDatagroupDto, "q_", true);
        sysDatagroupDto.setIsEnable(1);
        List<SysDatagroup> datagroupList = datagroupService.selectList(sysDatagroupDto);
        JSONData jsonData = new JSONData(datagroupList);
        return jsonData;
    }


    private List<SysDeptment> getDeptTreeListByGroupIdAndProjectId(long groupId, int dataStatusEnable, long projectId){
        String sql="SELECT DISTINCT a.* FROM (SELECT sd.dept_id as deptId,sd.dept_name as deptName,sd.pid as pid FROM sys_deptment AS sd LEFT JOIN  sys_project_dept AS spd ON sd.dept_id = spd.dept_id WHERE 1=1 and sd.group_id = " + groupId + " AND sd.data_status = " + dataStatusEnable + "  AND spd.project_id = " + projectId+ " UNION " +
                "select DISTINCT dept.dept_id as deptId,dept.dept_name as deptName,dept.pid as pid from sys_deptment dept,sys_project_deptment_rel pro where  dept.dept_id=pro.dept_id  and dept.group_id ="+groupId+" and pro.project_id="+projectId+" and dept.pid is null)a";
        return deptmentService.selectList(sql).parallelStream().map(s -> {
            SysDeptment sysDeptment = new SysDeptment();
            if (s.get("pid") == null) {
                sysDeptment.setPid(null);
            } else {
                sysDeptment.setPid(Long.valueOf(Objects.toString(s.get("pid"))));
            }
            sysDeptment.setDeptId(Long.valueOf(Objects.toString(s.get("deptId"))));
            sysDeptment.setDeptName(Objects.toString(s.get("deptName")));
            return sysDeptment;
        }).collect(Collectors.toList());
    }

    private List<TreeNode> deptListToTree(List<SysDeptment> deptList, List<String> deptIds) {
        List<TreeNode> treeList = new ArrayList<>();
        logger.error("liujw-当前站点未导入的部门：{}",StringUtils.join(deptList,","));
        logger.error("liujw-当前站点已导入的部门id：{}",StringUtils.join(deptIds,","));
        deptList.stream().filter(sysDeptment -> sysDeptment.getPid() == null).forEach(sysDeptment -> {
            String deptId = Objects.toString(sysDeptment.getDeptId());
            TreeNode treeNode = new TreeNode();
            treeNode.setId(Objects.toString(sysDeptment.getDeptId()));
            treeNode.setText(sysDeptment.getDeptName());
            treeNode.setExpanded(false);
            // 只有子节点会被勾上。
            boolean check = checkChildNode2(deptId);
            if (check && !CollectionUtils.isEmpty(deptIds) && deptIds.contains(deptId)) {return;};
            treeList.add(findChildren(treeNode, deptList, deptIds));
        });
        return treeList;
    }


    private TreeNode findChildren(TreeNode parent, List<SysDeptment> deptList, List<String> deptIds) {
        deptList.stream().filter(sysDeptment -> sysDeptment.getPid() != null && parent.getId().equals(sysDeptment.getPid().toString())).forEach(sysDeptment -> {
                    TreeNode treeNode = new TreeNode();
                    String deptId = Objects.toString(sysDeptment.getDeptId());
                    treeNode.setId(sysDeptment.getDeptId().toString());
                    treeNode.setText(sysDeptment.getDeptName());
                    treeNode.setExpanded(false);
                    boolean check = checkChildNode2(deptId);
                    if (check && !CollectionUtils.isEmpty(deptIds) && deptIds.contains(deptId)) {return;};
                    parent.addNode(findChildren(treeNode, deptList, deptIds));
                }
        );
        return parent;
    }
    /**
     * 当前节点是否是子节点
     *
     * @param deptId
     * @return
     */
    private Boolean checkChildNode2(String deptId) {

        long count = countByPidAndDataStatus(Long.valueOf(deptId), ApplicationGlobalNames.DATA_STATUS_ENABLE);
        // 当前节点是子节点
        if (count == 0) {
            return true;
        } else if (count > 0) {
            return false;
        } else {
            return false;
        }
    }

    private Long countByPidAndDataStatus(Long deptId,int dataStatus){
        Long count=0L;
        SysDeptment dept=new SysDeptment();
        dept.setPid(deptId);
        dept.setDataStatus((short) dataStatus);
        String sql="select count(*) as count from sys_deptment where pid="+deptId+" and data_status="+dataStatus;
        Map<String, Object> countMap = deptmentService.findOne(sql);
        if(!CollectionUtils.isEmpty(countMap)){
            count= (Long) countMap.get("count");
        }
        return count;
    }
}
